package com.jed.xxh.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jed.xxh.R;
import com.jed.xxh.activity.CourierActivity;
import com.jed.xxh.activity.LoginActivity;
import com.jed.xxh.activity.PhoneActivity;
import com.jed.xxh.entity.MyUser;
import com.jed.xxh.utils.L;
import com.jed.xxh.utils.ShareUtil;
import com.jed.xxh.utils.StaticClass;
import com.jed.xxh.utils.T;
import com.jed.xxh.utils.UtilTools;
import com.jed.xxh.view.CustomDialog;

import java.io.File;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 项目名：stewardAPP<br/>
 * 包名：  com.jed.xxh.fragment<br/>
 * 文件名：UserFragment<br/>
 * 作者：徐晓辉<br/>
 * 创建日期：2018/11/24 14:04<br/>
 * 描述：个人中心<br/>
 */
public class UserFragment extends Fragment implements View.OnClickListener {

    public static final String PHOTO_IMAGE_FILE_NAME = "fileImg.jpg";
    public static final int CAMERA_REQUEST_CODE = 100;//相机
    public static final int IMAGE_REQUEST_CODE = 101;//相册
    public static final int RESULT_REQUEST_CODE = 102;
    private File file = null;
    private TextView edit_user;//编辑用户信息
    private EditText et_userName;
    private EditText et_userSex;
    private EditText et_userAge;
    private EditText et_userDesc;
    private Button confirm_the_change;//确认修改
    private Button out_login;//退出登录
    private CircleImageView profile_image;//圆形头像
    private CustomDialog dialog;//点击头像后弹出提示框
    //提示框按钮
    private Button btn_camera;
    private Button btn_picture;
    private Button btn_cancel;

    //点击查询物流信息
    private TextView tv_courier;
    //点击查询手机号码归属地
    private TextView tv_phone;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, null);
        initView(view);
        return view;
    }

    /**
     * 初始化
     */
    private void initView(View view) {
        //用户相关
        out_login = view.findViewById(R.id.out_login);
        out_login.setOnClickListener(this);
        edit_user = view.findViewById(R.id.edit_user);
        edit_user.setOnClickListener(this);
        et_userName = view.findViewById(R.id.et_userName);
        et_userSex = view.findViewById(R.id.et_userSex);
        et_userAge = view.findViewById(R.id.et_userAge);
        et_userDesc = view.findViewById(R.id.et_userDesc);
        confirm_the_change = view.findViewById(R.id.confirm_the_change);
        confirm_the_change.setOnClickListener(this);

        profile_image = view.findViewById(R.id.profile_image);
        profile_image.setOnClickListener(this);

        dialog = new CustomDialog(getActivity(), 50, 0,
                R.layout.dialog_photo, R.style.pop_anim_style, Gravity.CENTER, R.style.pop_anim_style);
        dialog.setCancelable(false);//设置屏幕外点击无效

        btn_camera = dialog.findViewById(R.id.btn_camera);
        btn_picture = dialog.findViewById(R.id.btn_picture);
        btn_cancel = dialog.findViewById(R.id.btn_cancel);
        btn_camera.setOnClickListener(this);
        btn_picture.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);

        //设置输入框不可点击
        setEnabled(false);
        MyUser user = BmobUser.getCurrentUser(MyUser.class);
        et_userName.setText(user.getUsername());
        et_userSex.setText(user.getSex() ? "男" : "女");
        et_userAge.setText(String.valueOf(user.getAge()));
        et_userDesc.setText(user.getDesc());

        //初始化用户头像
        String user_avatar = ShareUtil.getString(StaticClass.USER_AVATAR, "");
        UtilTools.getImageToShare(getActivity(), profile_image, user_avatar);

        //物流
        tv_courier = view.findViewById(R.id.tv_courier);
        tv_courier.setOnClickListener(this);

        //手机号码归属地
        tv_phone = view.findViewById(R.id.tv_phone);
        tv_phone.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_phone://查询物流信息
                L.i("点击了查询手机号码归属地========");
                startActivity(new Intent(getActivity(), PhoneActivity.class));
                break;
            case R.id.tv_courier://查询物流信息
                L.i("点击了查询物流信息========");
                startActivity(new Intent(getActivity(), CourierActivity.class));
                break;
            case R.id.btn_camera://拍照
                toCamera();
                break;
            case R.id.btn_picture://图库
                toPicture();
                break;
            case R.id.btn_cancel://取消按钮
                dialog.dismiss();
                break;
            case R.id.profile_image:
                dialog.show();
                L.i("点击了更换头像按钮");
                break;
            case R.id.edit_user://点击编辑资料
                confirm_the_change.setVisibility(View.VISIBLE);
                setEnabled(true);
                et_userName.setFocusable(true);
                int length = et_userName.getText().toString().length();
                et_userName.setSelection(length);
                break;
            case R.id.confirm_the_change://点击确认修改
                updateUser();
                break;
            case R.id.out_login://退出登录
                MyUser.logOut();   //清除缓存用户对象
                BmobUser currentUser = MyUser.getCurrentUser(); // 现在的currentUser是null了
                L.i("退出登录");
                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
                break;
        }
    }

    /**
     * 更新用户信息
     */
    private void updateUser() {
        String userName = et_userName.getText().toString().trim();
        String userSex = et_userSex.getText().toString().trim();
        String userAge = et_userAge.getText().toString().trim();
        String userDesc = et_userDesc.getText().toString().trim();
        MyUser myUser = new MyUser();
        myUser.setUsername(userName);
        myUser.setSex("男".equals(userSex));
        myUser.setAge(Integer.parseInt(userAge));
        myUser.setDesc(userDesc);
        BmobUser bmobUser = BmobUser.getCurrentUser();

        myUser.update(bmobUser.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    setEnabled(false);
                    confirm_the_change.setVisibility(View.GONE);
                    T.showShortToast("修改成功");
                    L.i("用户信息编辑保存成功");
                } else {
                    T.showShortToast("修改失败");
                    L.i("用户信息编辑保存失败");
                }
            }
        });
    }

    /**
     * 跳转到相册
     */
    private void toPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
        dialog.dismiss();
    }

    /**
     * 跳转到相机
     */
    private void toCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //判断内存卡是否可用
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_IMAGE_FILE_NAME)));
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
        dialog.dismiss();
    }

    /**
     * 拍照或选择照片后返回数据
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != getActivity().RESULT_CANCELED) {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE://相册数据
                    startPhotoZoom(data.getData());
                    break;
                case CAMERA_REQUEST_CODE://相机数据
                    file = new File(Environment.getExternalStorageDirectory(), PHOTO_IMAGE_FILE_NAME);
                    startPhotoZoom(Uri.fromFile(file));
                    break;
                case RESULT_REQUEST_CODE:
                    if (data != null) {
                        setImageToView(data);
                        //如果已经裁剪了新的照片，那么久删除原来的照片
                        if (file != null) {
                            file.delete();
                        }
                    }
                    break;
            }
        }

    }


    /**
     * 裁剪照片
     */
    public void startPhotoZoom(Uri uri) {
        if (uri == null) {
            L.e("Uri == null");
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //设置裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪图片的质量
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        //发送数据
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    /**
     * 设置图片
     */
    private void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            profile_image.setImageBitmap(bitmap);
        }
    }

    /**
     * 设置输入框是否可编辑
     */
    private void setEnabled(boolean enabled) {
        et_userName.setEnabled(enabled);
        et_userSex.setEnabled(enabled);
        et_userAge.setEnabled(enabled);
        et_userDesc.setEnabled(enabled);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        UtilTools.putImageToShare(getActivity(), profile_image);
    }
}
